package com.jacobson.huobi.components.breathing

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.view.View
import com.jacobson.core.utils.DeviceUtil
import kotlin.math.abs

class BreathingLightView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {
    private val paint = Paint(Paint.ANTI_ALIAS_FLAG)
    private var bgAlpha = 255

    var status: Int = 0
        set(value) {
            field = value
            invalidate()
        }

    var color: Int = Color.WHITE
        set(value) {
            field = value
            invalidate()
        }

    init {
        paint.isAntiAlias = true
    }

    fun setBgAlpha(alpha: Int) {
        this.bgAlpha = alpha
    }

    override fun onDraw(canvas: Canvas) {
        val centerX = (width - paddingStart - paddingEnd) / 2.0f
        val centerY = (height - paddingTop - paddingBottom) / 2.0f
        paint.color = if (status == 1) color else Color.GRAY
        paint.alpha = if (status == 1) bgAlpha else 255
        if (status == 1) {
            canvas.drawCircle(centerX, centerY, radius, paint)
        } else {
            paint.isFakeBoldText = true
            paint.textSize = DeviceUtil.dp2px(7f).toFloat()
            // 计算文字BaseLine
            val textBaseY = height / 2 + (abs(paint.ascent()) - paint.descent()) / 2
            val measureText = paint.measureText("X")
            canvas.drawText("X", centerX - measureText / 2.0F, textBaseY, paint)
        }
        super.onDraw(canvas)
    }

    private val radius = DeviceUtil.dp2px(2.5f).toFloat()
}